<template>
  <div ref="editor" class="text-editor"></div>
</template>

<script lang="ts">
import { uploadCourseImage } from '@/services/course';
import Vue from 'vue';
import E from 'wangeditor';

export default Vue.extend({
  name: 'TextEditor',
  props: {
    value: {
      type: String,
      default: '',
    },
  },
  watch: {
    value: function() {
      this.initEditor();
    },
  },
  data() {
    return {
      editor: null as any,
    };
  },
  // 组件已经渲染好，可以初始化操作 DOM 了
  mounted() {
    this.initEditor();
  },
  methods: {
    initEditor() {
      if (!this.editor) {
        this.editor = new E(this.$refs.editor as any);
        // 注意：事件监听必须在 create 之前
        this.editor.config.onchange = (value: string) => {
          this.$emit('input', value);
        };
        this.editor.create();

        // 提交图片
        this.editor.config.customUploadImg = async function(
          resultFiles: any,
          insertImgFn: any
        ) {
          // 1. 把用户选择的 resultFiles 上传到服务端
          const fd = new FormData();
          fd.append('file', resultFiles[0]);

          const { data } = await uploadCourseImage(fd);

          insertImgFn(data.data.name);
        };
      }
      // 注意：设置初始化必须在 create 之后
      this.editor.txt.html(this.value);
    },
  },
});
</script>

<style lang="scss" scoped></style>
